#include "CodeEditorAnimator.h"

namespace CodeEdit {

CodeEditorAnimator::CodeEditorAnimator(QObject *parent)
        :QObject(parent)
{
    _value = 0;
    _timeline = new QTimeLine(256, this);
    _timeline->setCurveShape(QTimeLine::SineCurve);
    connect(_timeline, SIGNAL(valueChanged(qreal)), this, SLOT(step(qreal)));
    connect(_timeline, SIGNAL(finished()), this, SLOT(deleteLater()));
    _timeline->start();
}


void CodeEditorAnimator::setData(QFont f, QPalette pal, const QString &text)
{
    _font = f;
    _palette = pal;
    _text = text;
    QFontMetrics fm(_font);
    _size = QSizeF(fm.width(_text), fm.height());
}

void CodeEditorAnimator::draw(QPainter *p, const QPointF &pos)
{
    _lastDrawPos = pos;
    p->setPen(_palette.text().color());
    QFont f = _font;
    f.setPointSizeF(f.pointSizeF() * (1.0 + _value/2));
    QFontMetrics fm(f);
    int width = fm.width(_text);
    QRectF r((_size.width()-width)/2, (_size.height() - fm.height())/2, width, fm.height());
    r.translate(pos);
    p->fillRect(r, _palette.base());
    p->setFont(f);
    p->drawText(r, _text);
}

bool CodeEditorAnimator::isRunning() const
{
    return _timeline->state() == QTimeLine::Running;
}

QRectF CodeEditorAnimator::rect() const
{
    QFont f = _font;
    f.setPointSizeF(f.pointSizeF() * (1.0 + _value/2));
    QFontMetrics fm(f);
    int width = fm.width(_text);
    return QRectF((_size.width()-width)/2, (_size.height() - fm.height())/2, width, fm.height());
}

void CodeEditorAnimator::step(qreal v)
{
    QRectF before = rect();
    _value = v;
    QRectF after = rect();
    emit updateRequest(_position, _lastDrawPos, before.united(after));
}

void CodeEditorAnimator::finish()
{
    _timeline->stop();
    step(0);
    deleteLater();
}

} // namespace CodeEdit
